package com.lsb.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsb.pojo.Submit;
import com.lsb.response.Result;
import com.lsb.service.SubmitService;
import com.lsb.service.UserService;
import com.lsb.utils.MyJsonUtils;
import com.lsb.vo.SubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liusibo
 * @since 2021-06-10
 */
@RestController
@Slf4j
public class SubmitController {

    @Autowired
    UserService userService;

    @Autowired
    SubmitService submitService;

    @GetMapping("/excel")
    @PreAuthorize("hasRole('admin')")
    void excel(HttpServletResponse response)throws Exception{
        List<Submit> submitList = submitService.list();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        //显示给前端的打卡数据submitVO
        List<SubmitVO> submitVOList = new ArrayList<>();
        //过滤日期不是今天的健康打卡数据
        List<Submit> collect = submitList.stream().filter(submit -> {
            boolean equals = sdf.format(submit.getCreateTime()).equals(sdf.format(new Date()));
            return equals;
        }).collect(Collectors.toList());
        //装入SubmitVO给前端回显打卡数据
        collect.forEach(submit -> submitVOList.add(new SubmitVO(
                submit.getUserId(),submit.getUsername(),submit.getRealName()
                ,submit.getTelephoneNumber(),submit.getIdentityNumber()
                ,submit.getTemperature(),sdf.format(submit.getCreateTime())
                ,submit.getIsSubmit()==1?"已提交":"未提交"
        )));

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), SubmitVO.class).sheet("模板").doWrite(submitVOList);
        log.info("导出excel");
    }

    @PostMapping("/submitForm")
    @PreAuthorize("hasAnyRole('user','admin')")
    void submitForm(@RequestBody Submit submit, HttpServletResponse response)throws Exception{
        Submit submitToday = submitService.getById(submit.getId());
        if(submitToday.getIsSubmit()==1){
            Result result = Result.error().message("不要尝试进行重复提交");
            MyJsonUtils.WriteJSON(response,result);
        }
        else {
            //打卡记录设置为已提交
            submit.setIsSubmit(1);
            submitService.updateById(submit);
            //返回json格式数据给前端
            Result result = Result.ok().message("提交成功");
            MyJsonUtils.WriteJSON(response,result);
        }
    }


    //今日打卡数据
    @GetMapping("/todaySubmit")
    @PreAuthorize("hasAnyRole('admin')")
    void getTodaySubmit(HttpServletResponse response)throws Exception{
        submitService.getTodaySubmit(response);
    }

    //今日统计图表数据
    @GetMapping("/todayChart")
    @PreAuthorize("hasAnyRole('admin')")
    void todayChart(HttpServletResponse response)throws Exception{
        submitService.getTodayChart(response);
    }

    //所有打卡数据
    @GetMapping("/allSubmit")
    @PreAuthorize("hasAnyRole('admin')")
    void getAllSubmit(HttpServletResponse response)throws Exception{
        submitService.getAllSubmit(response);
    }

    //分页查询所有打卡数据,{currentPage}当前页码,{pageSize}一页多少条数据
    @GetMapping("/allSubmit/{currentPage}/{pageSize}")
    @PreAuthorize("hasAnyRole('admin')")
    void getAllSubmitPage(@PathVariable("currentPage") Integer current,@PathVariable("pageSize") Integer size,HttpServletResponse response)throws Exception{
        Page<Submit> page = new Page<>(current,size);
        Page<Submit> submitPage = submitService.page(page);
        long total = submitPage.getTotal();
        List<Submit> submitList = submitPage.getRecords();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        //显示给前端的打卡数据submitVO
        List<SubmitVO> submitVOList = new ArrayList<>();
        //过滤掉第二天的数据,如果存在的话,由于定时任务的原因,有可能已经存在第二天的数据
        List<Submit> collect = submitList.stream().filter(submit -> {
            int i = sdf.format(submit.getCreateTime()).compareTo(sdf.format(new Date()));
            return i <= 0;
        }).collect(Collectors.toList());
        //装入SubmitVO给前端回显打卡数据
        collect.forEach(submit -> submitVOList.add(new SubmitVO(
                submit.getUserId(),submit.getUsername(),submit.getRealName()
                ,submit.getTelephoneNumber(),submit.getIdentityNumber()
                ,submit.getTemperature(),sdf.format(submit.getCreateTime())
                ,submit.getIsSubmit()==1?"已提交":"未提交"
        )));
        //返回json格式数据给前端
        Result result = Result.ok().message("所有打卡数据").data("tableData",submitVOList).data("total",total-userService.list().size());
        if(total==0){
            MyJsonUtils.WriteJSON(response,Result.error().message("没有数据"));
        }
        else {
            MyJsonUtils.WriteJSON(response,result);
        }
    }

    //根据日期筛选打卡数据
    @GetMapping("/dateSubmit")
    @PreAuthorize("hasAnyRole('admin')")
    void getDateSubmit(@RequestParam("date")String date, HttpServletResponse response)throws Exception{
        String[] split = date.substring(0, 10).split("-");
        int year = Integer.parseInt(split[0]);
        int month = Integer.parseInt(split[1]);
        int day = Integer.parseInt(split[2]);
        Calendar calendar = Calendar.getInstance();//获取一个日历实例
        calendar.set(year, month-1, day);//设定日历的日期
        //由于前端elementUI的时间选择器是显示前一天的0:00，所以要得到下一天的日期
        calendar.add(Calendar.DATE, +1);
        String strDateFormat = "yyyy年MM月dd日";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String date1 = sdf.format(calendar.getTime());
        log.info("根据日期拿到打卡数据:"+date1);
        submitService.getDateSubmit(date1,response);
    }

    //在当前表格中根据学号进行模糊查询
    @PostMapping("/queryByUsername")
    @PreAuthorize("hasAnyRole('admin')")
    void getSubmitByUsernameMohu(@RequestBody Map<String,Object> datas, HttpServletResponse response)throws Exception{
        log.info("学号模糊查询-当前表格数据:"+datas.get("submitList"));
        log.info("学号模糊查询-当前的学号:"+datas.get("username"));
        List<LinkedHashMap> list = (List<LinkedHashMap>) datas.get("submitList");
        String username = (String) datas.get("username");
        submitService.getSubmitByUsernameMohu(list,username,response);
    }

    //筛选异常体温名单
    @PostMapping("/abnormalTemperature")
    @PreAuthorize("hasAnyRole('admin')")
    void getAbnormalTemperature(@RequestBody List<SubmitVO> submitList, HttpServletResponse response)throws Exception{
        log.info("前端axios post传来的Object Array数据(筛选体温异常): "+submitList);
        submitService.getAbnormalTemperature(submitList, response);
    }

    //筛选未提交名单
    @PostMapping("/uncommitted")
    @PreAuthorize("hasAnyRole('admin')")
    void getUncommitted(@RequestBody List<SubmitVO> submitList, HttpServletResponse response)throws Exception{
        log.info("前端axios post传来的Object Array数据(筛选未提交): "+submitList);
        submitService.getUncommitted(submitList,response);
    }

}

